#!/usr/bin/env python
import os
import os.path
import sys
from gtk import *
import Image as PIL
from xmmsclient import *
import xmmsclient.glib

class CoverView(VBox):
    hash = 0
    
    def __init__(self, xmms2):
        VBox.__init__(self)
        
        self.xmms2 = xmms2
        self.image = Image()
        self.pack_start(self.image)
        self.set_cover = lambda *args: xmms2.playback_current_id(
            cb=self.set_cover_cb)
        self.xmms2.broadcast_playback_current_id(self.set_cover)
        
    def set_cover_parse(self, res):
        if res.iserror():
            print "error parsing id info"
            return
        tag = res.value()
        try:
            hash = tag["picture_front"]
        except KeyError:
            print "Could not set cover. No hash"
            return
        if self.hash == hash:
            return
        else:
            self.hash = hash
        self.xmms2.bindata_retrieve(hash, cb=self.on_data_received)
        
    def set_cover_cb(self, res):
        if res.iserror():
            print "error on set_cover_cb"
            return
        id = res.value()
        self.xmms2.medialib_get_info(id, cb=self.set_cover_parse)
        
    def on_data_received(self, res):
        if res.iserror():
            print "could not receive cover!"
            return
        data = res.value()
        f = open("/tmp/cover.jpg", 'w')
        print >>f, data
        f.flush()
        f.close()
        self.image.set_from_file("/tmp/cover.jpg")
        
        
if __name__ == "__main__":
    xmms2 = XMMS("coverviewer")

    try:
        xmms2.connect(os.getenv("XMMS_PATH"))
    except:
        exit(1)

    xmmsclient.glib.GLibConnector(xmms2)
    cv = CoverView(xmms2)
    cv.set_cover()
    w = Window()
    w.set_title("Xmms2 CoverViewer")
    w.add(cv)
    w.connect("delete-event", lambda *args: main_quit())
    w.show_all()
    main()
